import zipfile
import os
import urlparse
from pyurl.url import BaseURL, URL, scheme_registry
from pyurl.file import File
from pyurl.connection import Connection

class ArchiveConnection(Connection):
    def __init__(self):
        self.archive_url = None
        self.archive = None
        
    def open_archive(self, file):
        raise NotImplementedError()
        
    def open(self, url):
        self.archive_url = File(url.archive)
        self.archive =  self.open_archive(self.archive_url)
        
    def is_open(self):
        return self.archive is not None
    
    def close(self):
        if self.archive:
            self.archive_url.connection.close()
            self.archive_url = None
            self.archive.close()
            self.archive = None

class ArchiveURL(BaseURL):
    def __init__(self, url, child=None):
        BaseURL.__init__(self, url, child)
        path = urlparse.urlparse(url).path
        if len(path) == 0:
            self.archive = None
            self.path = None
        else:
            parts = path.split("!")
            if len(parts) < 2:
                self.archive = URL(parts[0])
                self.path = None
            else:
                self.archive = URL(parts[0])
                self.path = parts[1]
        if child:
            self.path = os.path.join(self._path, child)
        
    def get_parent(self):
        if self._path == "" or self._path == "/":
            return self._archive
        else:
            return BaseURL.get_parent(self)
        
    def __str__(self):
        return self._scheme+":"+str(self._archive)+"!"+self._path
        
    def get_archive(self):
        return self._archive
    
    def set_archive(self, archive):
        if archive is None:
            self._archive = None
        else:
            if isinstance(archive, BaseURL):
                self._archive = archive
            else:
                self._archive = URL(archive)
    
    archive = property(get_archive, set_archive)
    parent = property(get_parent)